<?php

namespace App\Library\Logic;

use App\Models\ShopOrderExtModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ShopOrderExtLogic extends ShopOrderExtModel
{
    /**
     * add
     * @param Model $order
     * @param int $freight
     * @param int $addressId
     * @param int|null $couponUserRelatedId
     * @return void
     */
    public static function add(Model $order, int $freight, int $addressId, ?int $couponUserRelatedId = null): void
    {
        self::insertForModel([
            'statusPickup' => $order->order_is_self_pickup === 1,
            'orderId' => $order->order_id,
            'userId' => $order->buy_user_id,
            'sellerId' => $order->sell_user_id,
            'freight' => $freight,
            'addressId' => $addressId,
            'userRemark' => $order->order_note,
            'couponUserRelatedId' => $couponUserRelatedId ?? 0,
            'extend' => in_array(USERID, __('base.plugIdArr')) ? [
                'plug' => [
                    'nickname' => random(),
                    'mobile' => self::randMobile(),
                    'address' => self::randAddress(),
                ],
            ] : null,
        ]);
    }

    /**
     * tj
     * @return array
     */
    public static function tj(): array
    {
        $tj = self::query()->leftJoin('shop_order', 'shop_order.order_id', 'shop_order_ext.order_id')
            ->whereNull('shop_order_ext.system_at')
            ->where('shop_order.buy_user_id', '>', 0)
            ->groupBy('status')->pluck(DB::raw('count(*) as count'), 'status')->toArray();
        $tj[7] = self::query()->leftJoin('shop_order', 'shop_order.order_id', 'shop_order_ext.order_id')
            ->whereNull('shop_order_ext.system_at')
            ->where('shop_order.buy_user_id', '>', 0)
            ->whereIn('status_after_sale', [1, 2])->whereNull('refund_at')->count();
        $tj[8] = ShopOrderReturnLogic::query()->where('or_buy_status', 4)->count();
        return $tj;
    }

    private static function randMobile(): string
    {
        $arr = __('base.mobilePrefix');
        return '1' . $arr[array_rand($arr)] . random(9, 1);
    }

    private static function randAddress(): string
    {
        $province = AreaLogic::query()->where('parent_id', 0)->whereNotIn('id', [26, 31])->orderByRaw('rand()')
            ->first(['id', 'name']);
        $city = AreaLogic::query()->where('parent_id', $province->id)->orderByRaw('rand()')->first(['id', 'name']);
        $district = AreaLogic::query()->where('status', 1)->where('parent_id', $city->id)->orderByRaw('rand()')
            ->value('name');
        return $province->name . $city->name . $district;
    }
}
